﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.Common;
using DuocThaiBinh.HtmlHelpers;
using Newtonsoft.Json;

namespace DuocThaiBinh.Controllers
{
    public class ChuyenKhoController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        //
        // GET: /ChuyenKho/
        [Authorize(Roles="Administrator")]
        public ActionResult Index()
        {
            var chuyenkhoes = db.ChuyenKhoes.Include(c => c.Kho).Include(c => c.Kho1).OrderBy(m => m.CodeChuyen);
            return View(chuyenkhoes.ToList());
        }

        [Authorize(Roles = "Administrator")]
        public JsonResult IndexGetGrid(int page, int rows, string sidx, string sord, string from, string to, string filters, bool _search, string masp)
        {
            var chuyenkhoes = db.ChuyenKhoes.OrderByDescending(p => p.CodeChuyen).ToList() as IEnumerable<ChuyenKho>;

            var count = chuyenkhoes.Count<ChuyenKho>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = chuyenkhoes.Skip(rows * (page - 1)).Take(rows).ToList();


            return Json(new
            {
                page = page,
                total = total,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.CodeChuyen, x.Time })
            }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /ChuyenKho/Create
        [Authorize(Roles = "Administrator")]
        public ActionResult Create()
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            ChuyenKho chuyenkho = db.ChuyenKhoes.Where(p => p.ID != null).OrderByDescending(p => p.CodeChuyen).FirstOrDefault();
            string mahd = string.Empty;
            if (chuyenkho != null)
            {
                var MaNKLast = chuyenkho.CodeChuyen.Split(new string[] { "-" }, StringSplitOptions.None);
                if (Convert.ToInt32(MaNKLast[MaNKLast.Length - 2]) == DateTime.Now.Month)
                {
                    var intMaSPnew = Convert.ToInt32(MaNKLast[MaNKLast.Length - 1]) + 1;
                    mahd = "C-" + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + string.Format("{0:00000}", intMaSPnew);
                }
                else
                {
                    mahd = "C-" + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
                }
            }
            else
            {
                mahd = "C-" + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
            }

            ViewBag.MaHD = mahd;
            List<Kho> khoes = new List<Kho>();
            foreach (var userInCuaHang in currentUser.UserInCuaHangs)
            {
                khoes.AddRange(userInCuaHang.CuaHang.Khoes);
            }
            ViewBag.NewKhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.OldKhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View();
        }

        //
        // POST: /ChuyenKho/Create
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Create(ChuyenKho chuyenkho, FormCollection form)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            string masp = string.Empty;
            string soluong = string.Empty;
            string donvi = string.Empty;

            List<string> listmasp = new List<string>();
            List<int> listsoluong = new List<int>();
            string khoID = string.Empty;

            if (ModelState.IsValid)
            {
                foreach (string key in form.AllKeys)
                {
                    if (key.Contains("ma_sp"))
                    {
                        masp += form[key] + ";#";
                        listmasp.Add(form[key]);
                    }
                    if (key.Contains("SoLuong_"))
                    {
                        soluong += form[key] + ";#";
                        var valueSL = form[key];
                        int intValueSL = 0;
                        if (int.TryParse(valueSL, out intValueSL))
                        {
                            listsoluong.Add(intValueSL);
                        }
                    }
                }
                // update so luong san pham
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                    SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == chuyenkho.OldKhoID).FirstOrDefault();
                    if (sanPhamInKho != null)
                    {
                        sanPhamInKho.SoLuong -= listsoluong[i];
                        db.Entry(sanPhamInKho).State = EntityState.Modified;
                        db.SaveChanges();
                    }

                    SanPhamInKho sanPhamInKho1 = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == chuyenkho.NewKhoID).FirstOrDefault();
                    if (sanPhamInKho1 != null)
                    {
                        sanPhamInKho1.SoLuong += listsoluong[i];
                        db.Entry(sanPhamInKho1).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        sanPhamInKho1 = new SanPhamInKho();
                        sanPhamInKho1.KhoID = chuyenkho.NewKhoID;
                        sanPhamInKho1.SanPhamID = sp.ID;
                        sanPhamInKho1.SoLuong = listsoluong[i];
                        db.SanPhamInKhoes.Add(sanPhamInKho1);
                        db.SaveChanges();
                    }
                }

                chuyenkho.SanPhamID = masp;
                chuyenkho.SoLuong = soluong;

                //Tao moi chuyen kho
                db.ChuyenKhoes.Add(chuyenkho);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            List<Kho> khoes = new List<Kho>();
            foreach (var userInCuaHang in currentUser.UserInCuaHangs)
            {
                khoes.AddRange(userInCuaHang.CuaHang.Khoes);
            }
            ViewBag.NewKhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.OldKhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;

            return View(chuyenkho);
        }

        //
        // GET: /ChuyenKho/Edit/5
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id = 0)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            ChuyenKho chuyenkho = db.ChuyenKhoes.Find(id);
            if (chuyenkho == null)
            {
                return HttpNotFound();
            }

            var masp = chuyenkho.SanPhamID;
            var soluong = chuyenkho.SoLuong;
            var listmasanpham = masp.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listmasp = listmasanpham;
            ViewBag.listsoLuong = soluong.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.stt = listmasanpham.Length;

            ViewBag.MaHD = chuyenkho.CodeChuyen;
            ViewBag.NewTenKho = chuyenkho.Kho1.TenKho;
            ViewBag.OldTenKho = chuyenkho.Kho.TenKho;
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View(chuyenkho);
        }

        //
        // POST: /ChuyenKho/Edit/5
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult Edit(ChuyenKho chuyenkho, FormCollection form)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            //remove old infomation
            var oldCK = db.ChuyenKhoes.Find(chuyenkho.ID);
            var old_Masp = oldCK.SanPhamID;
            var old_SoLuong = oldCK.SoLuong;

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(old_Masp))
                {
                    var list_old_Masp = old_Masp.Split(new string[] { ";#" }, StringSplitOptions.None);
                    var list_old_SoLuong = old_SoLuong.Split(new string[] { ";#" }, StringSplitOptions.None);
                    for (int i = 0; i < list_old_Masp.Length; i++)
                    {

                        string sp_old_sp = list_old_Masp[i];
                        if (!string.IsNullOrEmpty(sp_old_sp))
                        {
                            SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
                            SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == chuyenkho.OldKhoID).FirstOrDefault();
                            if (sanPhamInKho != null)
                            {
                                sanPhamInKho.SoLuong += Convert.ToInt32(list_old_SoLuong[i]);
                                db.Entry(sanPhamInKho).State = EntityState.Modified;
                                db.SaveChanges();
                            }

                            SanPhamInKho sanPhamInKho1 = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == chuyenkho.NewKhoID).FirstOrDefault();
                            if (sanPhamInKho1 != null)
                            {
                                sanPhamInKho1.SoLuong -= Convert.ToInt32(list_old_SoLuong[i]);
                                db.Entry(sanPhamInKho1).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }
                }
                string masp = string.Empty;
                string soluong = string.Empty;
                List<string> listmasp = new List<string>();
                List<int> listsoluong = new List<int>();
                foreach (string key in form.AllKeys)
                {
                    if (key.Contains("ma_sp"))
                    {
                        masp += form[key] + ";#";
                        listmasp.Add(form[key]);
                    }
                    if (key.Contains("SoLuong_"))
                    {
                        soluong += form[key] + ";#";
                        listsoluong.Add(Convert.ToInt32(form[key]));
                    }
                }
                //update so luong
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                    SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == chuyenkho.OldKhoID).FirstOrDefault();
                    if (sanPhamInKho != null)
                    {
                        sanPhamInKho.SoLuong -= Convert.ToInt32(listsoluong[i]);
                        db.Entry(sanPhamInKho).State = EntityState.Modified;
                        db.SaveChanges();
                    }

                    SanPhamInKho sanPhamInKho1 = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == chuyenkho.NewKhoID).FirstOrDefault();
                    if (sanPhamInKho1 != null)
                    {
                        sanPhamInKho1.SoLuong += Convert.ToInt32(listsoluong[i]);
                        db.Entry(sanPhamInKho1).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                
                chuyenkho.SanPhamID = masp;
                chuyenkho.SoLuong = soluong;
                this.db.Entry<ChuyenKho>(oldCK).CurrentValues.SetValues(chuyenkho);

                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.NewTenKho = chuyenkho.Kho1.TenKho;
            ViewBag.OldTenKho = chuyenkho.Kho.TenKho;
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View(chuyenkho);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}